<?php


namespace app\shop\service\chat;


use app\shop\common\consts\Consts;
use app\shop\common\consts\RedisKey;
use app\shop\model\chat\GroupUserModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\ChatUserModel;
use app\shop\model\user\UserModel;
use app\shop\service\BaseService;
use GatewayClient\Gateway;
use think\facade\Cache;
use think\facade\Db;


class ChatUserService extends BaseService
{

    public static function getInstance()
    {
        return new ChatUserModel();
    }

    public function __construct()
    {
        $this->model = new ChatUserModel();
    }

    /**
     * 群信息
     * @param $chatSign
     * @return array|mixed|\think\Model|null
     * @throws \Exception
     */
    public function getGroupInfo($chatSign)
    {
        try {
            $info = $this->getOneLineByField('chat_sign', $chatSign);
            if (!$info) {
                return [];
            }
            $info['order_name'] = OrderModel::where('id', $info['order_id'])->value('order_name');
            return $info;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 修改群名
     * @param $chatSign
     * @param $userInfo
     * @param $title
     * @return bool
     * @throws \Exception
     */
    public function modifyGroupTitle($chatSign, $userInfo, $title)
    {
        try {
            $roleId = $userInfo['role_id'];
            if ($roleId != Consts::SERVICE_LEADER_ID) {
                throw new \Exception('您没有修改群名的权限');
            }
            return $this->updateOneLineByField('chat_sign', $chatSign, ['title' => $title]);
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 修改群公告
     * @param $chatSign
     * @param $userInfo
     * @param $notice
     * @return bool
     * @throws \Exception
     */
    public function modifyGroupArticle($chatSign, $userInfo, $notice)
    {
        try {
            $roleId = $userInfo['role_id'];
            if ($roleId != Consts::SERVICE_LEADER_ID) {
                throw new \Exception('您没有修改群公告的权限');
            }
            return $this->updateOneLineByField('chat_sign', $chatSign, ['notice' => $notice, 'notice_id' => Db::raw("notice_id+10")]);
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 加入群聊
     * @param $chatSign
     * @param $user
     * @return bool
     * @throws \Exception
     */
    public function joinGroup($chatSign, $user)
    {
        if (isPhoneNumber($user)) {
            $uid = UserModel::where('mobile', $user)->value('user_id');
            if (!$uid) {
                throw new \Exception('邀请的用户不存在');
            }
        } else {
            $uid = $user;
        }
        $chatGroupUser = GroupUserModel::where('chat_sign', $chatSign)
            ->where('user_id', $uid)
            ->find();
        if ($chatGroupUser) {
            throw new \Exception('用户已经在群聊中');
        }
        Gateway::$registerAddress = config('gateway.registerAddress');
        $clientIdArr = Gateway::getClientIdByUid($uid);
        if ($clientIdArr) {
            foreach ($clientIdArr as $clientId) {
                Gateway::joinGroup($clientId, $chatSign);
            }
        }
        $chatGroupUser = new GroupUserModel();
        $chatGroupUser->chat_sign = $chatSign;
        $chatGroupUser->user_id = $uid;
        $chatGroupUser->save();
        // 小于9人 重新生成头像
        if (GroupUserModel::where('chat_sign', $chatSign)->count() <= 9) {
            $chatGroupUserService = new ChatGroupUserService();
            $avatar = $chatGroupUserService->createGroupAvatar($chatSign);
            if ($avatar) {
                ChatUserModel::update(['avatar' => $avatar], ['chat_sign' => $chatSign]);
            }
        }

        // 放入redis set中
//        $redisKey = sprintf(RedisKey::USER_CHAT_GROUP_KEY, $uid);
//        $redisHandler = Cache::store('redis')->handler();
//        $redisHandler->SADD($redisKey, $chatSign);
        return true;
    }

    /**
     * T出群聊
     * @param $chatSign
     * @param $uids
     * @return bool
     * @throws \Exception
     */
    public function kickOutGroup($chatSign, $uids)
    {
        Gateway::$registerAddress = config('gateway.registerAddress');
        $chatInfo = $this->getOneLineByField('chat_sign', $chatSign);
        if (!$chatInfo) {
            throw new \Exception('群聊不存在');
        }
        $chatGroupUserCount = GroupUserModel::where('chat_sign', $chatSign)->count();
        if ($chatGroupUserCount <= 2) {
            throw new \Exception('请使用解散群聊功能');
        }
        $serviceId = UserModel::where('role_id', 3)->where('join_group', 1)->value('user_id');
        if (!$serviceId) {
            $serviceId = UserModel::where('role_id', 3)->max('user_id');
        }
        if (in_array($serviceId, $uids)) {
            throw new \Exception('不能移出管理员');
        }
        foreach ($uids as $uid) {
            $chatGroupUser = GroupUserModel::where('chat_sign', $chatSign)
                ->where('user_id', $uid)
                ->find();
            if ($chatGroupUser) {
                $chatGroupUser->delete();
            }
            $clientIdArr = Gateway::getClientIdByUid($uid);
            if ($clientIdArr) {
                $groupClintIdArr = Gateway::getClientIdListByGroup($chatSign);
                foreach ($clientIdArr as $clientId) {
                    if (in_array($clientId, $groupClintIdArr)) {
                        Gateway::leaveGroup($clientId, $chatSign);
                    }
                }
            }
            // 删除用户的群聊
//            $redisKey = sprintf(RedisKey::USER_CHAT_GROUP_KEY, $uid);
//            $redisHandler = Cache::store('redis')->handler();
//            $redisHandler->SREM($redisKey, $chatSign);
        }
        return true;

    }

    /**
     * 解散群聊
     * @param $chatSign
     * @return bool
     * @throws \Exception
     */
    public function dissolveGroup($chatSign)
    {
        // 删除群聊
        $chatInfo = $this->getOneLineByField('chat_sign', $chatSign);
        if (!$chatInfo) {
            throw new \Exception('群聊不存在');
        }
        $chatInfo->delete();
        // 删除群成员
        $chatGroupUser = GroupUserModel::where('chat_sign', $chatSign)->select();
        foreach ($chatGroupUser as $info) {
            GroupUserModel::destroy($info['id']);
            // 删除用户的群聊
            $redisHandler = Cache::store('redis')->handler();
//            $redisKey = sprintf(RedisKey::USER_CHAT_GROUP_KEY, $info['user_id']);
//            $redisHandler->SREM($redisKey, $chatSign);
            // 删除群聊最后信息
            $redisKey = sprintf(RedisKey::LAST_MESSAGE, $chatSign);
            $redisHandler->del($redisKey);
        }
        // 解散群聊
        Gateway::$registerAddress = config('gateway.registerAddress');
        Gateway::ungroup($chatSign);
        return true;
    }

    /**
     * 群成员
     * @param $chatSign
     * @return GroupUserModel[]|array|\think\Collection
     * @throws \Exception
     */
    public function groupUserArr($chatSign)
    {
        try {
            $arr = GroupUserModel::where('chat_sign', $chatSign)->order(['is_owner' => 'desc', 'id' => 'asc'])->select();
            $list = [];
            foreach ($arr as $value) {
                $userInfo = UserModel::find($value['user_id']);
                if (!$userInfo) {
                    continue;
                }
                $value['avatar'] = $userInfo['avatar'] ?? '';
                $value['realname'] = $userInfo['realname'] ?? '';
                $list[] = $value;
            }
            return $arr;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取群聊名称
     * @param $userRoleId
     * @param $chatUserInfo
     * @return mixed|string
     */
    public function getGroupTitle($userRoleId, $chatUserInfo)
    {
        if ($userRoleId == Consts::CUSTOMER_ID) {
            $title = $chatUserInfo['title'] ? $chatUserInfo['title'] : $chatUserInfo['order_name'];
        } else {
            $title = $chatUserInfo['order_name'] ? $chatUserInfo['order_name'] : '临时聊天';
        }
        return $title;
    }

    /**
     * 检测用户是否在群聊 如果不在则加入
     * @param $userId
     * @param $chatSign
     * @return bool
     */
    public function checkUserIsInGroup($userId, $chatSign)
    {
        Gateway::$registerAddress = config('gateway.registerAddress');
        $clientIdArr = Gateway::getClientIdByUid($userId);

        $onlineClientIdArr = Gateway::getClientIdListByGroup($chatSign);
        foreach ($clientIdArr as $client_id) {
            if (!in_array($client_id, $onlineClientIdArr)) {
                \GatewayWorker\Lib\Gateway::joinGroup($client_id, $chatSign);
            }
        }
        return true;
    }
}